package yancy.modules.sys.controller.stat;

import yancy.common.utils.R;
import yancy.modules.sys.controller.AbstractController;
import yancy.modules.sys.entity.Pair;
import yancy.modules.sys.service.SysBorrowBookService;
import yancy.modules.sys.service.SysBorrowLogService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.*;

/**
 * 数据统计接口
 *
 * @author dongyang
 * @since 2021-07-22 09:21
 */
@RestController
@RequestMapping("/chart")
@AllArgsConstructor
public class statisticController extends AbstractController {

    private final SysBorrowBookService borrowBookService;
    private final SysBorrowLogService borrowLogService;

    @RequestMapping("/line")
    public R getChartLine() {
        LocalDate now = LocalDate.now().plusDays(1);
        LocalDate weekAgo = now.minusDays(7);
        List<Pair> borrowCount = borrowBookService.queryCountByTime(weekAgo.toString(), now.toString());
        List<Pair> returnCount = borrowLogService.queryCountByTime(weekAgo.toString(), now.toString());
        Map<String ,List<Integer>> data = new HashMap<>();
        data.put("borrowCount", wrapResult(weekAgo, now, borrowCount));
        data.put("returnCount", wrapResult(weekAgo, now, returnCount));

        return R.ok().put("data", data);
    }

    private List<Integer> wrapResult(LocalDate startTime, LocalDate endTime, List<Pair> rawCountList) {
        Optional<Pair> found;
        List<Integer> ret = new ArrayList<>();

        while (startTime.isBefore(endTime)) {
            final LocalDate cur = startTime;
            found = rawCountList.stream().filter(e -> cur.toString().equals(e.getKey()))
                .findAny();
            ret.add(found.map(e -> Integer.valueOf(e.getValue())).orElse(0));

            startTime = startTime.plusDays(1);
        }
        return ret;
    }
}
